import React, { useState, useRef, useEffect } from 'react'
import { Link } from 'react-router-dom'
import { Input, Radio, Button, ConfigProvider, Flex, Upload, Avatar } from 'antd';
import { LoadingOutlined, PlusOutlined, UserOutlined } from '@ant-design/icons';
import { message } from 'antd';
import type { GetProp, UploadProps } from 'antd';
import axios from 'axios';

type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

const getBase64 = (img: FileType, callback: (url: string) => void) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result as string));
  reader.readAsDataURL(img);
};

const beforeUpload = (file: FileType) => {
  if (!file.type.startsWith('image/')) {
    message.error('只能上传图片文件！');
    return false;
  }
  return true;
};

// 自动处理图片为圆形（固定尺寸，无需弹窗裁剪）
const processImageToBase64 = (imageUrl: string): Promise<string> => {
  return new Promise((resolve, reject) => {
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    if (!ctx) return reject(new Error("获取Canvas上下文失败"));

    // 固定处理尺寸（平衡大小和清晰度）
    const size = 200;
    canvas.width = size;
    canvas.height = size;

    const img = new Image();
    img.src = imageUrl;
    img.crossOrigin = "anonymous";

    img.onload = () => {
      // 绘制圆形裁剪区域
      ctx.clearRect(0, 0, size, size);
      ctx.beginPath();
      ctx.arc(size / 2, size / 2, size / 2, 0, Math.PI * 2);
      ctx.clip(); // 裁剪为圆形

      // 按比例缩放图片，居中显示
      const aspectRatio = img.width / img.height;
      let drawWidth, drawHeight;
      
      if (aspectRatio >= 1) {
        drawHeight = size;
        drawWidth = size * aspectRatio;
      } else {
        drawWidth = size;
        drawHeight = size / aspectRatio;
      }

      const drawX = (size - drawWidth) / 2;
      const drawY = (size - drawHeight) / 2;
      ctx.drawImage(img, drawX, drawY, drawWidth, drawHeight);

      // 输出图片（平衡质量和大小）
      const base64 = canvas.toDataURL("image/jpeg", 0.85);
      resolve(base64);
    };

    img.onerror = () => reject(new Error("图片加载失败"));
  });
};

const Geren = () => {
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>('');

  const [formData, setFormData] = useState({
    编号: "",
    nickname: "",
    gender: 1,
    phone: "",
    avatar: ''
  });

  // 修改用户信息（包含base64头像）
  const updateUserInfo = async () => {
    try {
      const token = localStorage.getItem("token");
      if (!token) {
        message.warning("请先登录！");
        return;
      }

      const userParams = {
        avatar: imageUrl,
        gender: formData.gender,
        nickname: formData.nickname.trim() || formData.nickname,
        phone: formData.phone,
      };

      console.log("提交的用户信息:", {
        ...userParams,
        avatar: userParams.avatar ? `base64数据，长度: ${userParams.avatar.length}` : '空'
      });

      const res = await axios.patch(
        "http://localhost:8080/user",
        userParams,
        {
          headers: {
            Authorization: token,
            "Content-Type": "application/json",
          },
        }
      );

      console.log("用户信息修改成功：", res.data);

      // 更新本地存储
      try {
        localStorage.setItem('user_avatar', imageUrl || '');
        console.log('✅ 头像已更新到本地存储');

        const savedProfile = localStorage.getItem('userProfile');
        const processedNickname = userParams.nickname.trim();
        if (savedProfile) {
          const profile = JSON.parse(savedProfile);
          const updatedProfile = {
            ...profile,
            avatar: imageUrl,
            name: processedNickname,
            nickname: processedNickname
          };
          localStorage.setItem('userProfile', JSON.stringify(updatedProfile));
          console.log('✅ 姓名已更新到本地存储：', processedNickname);
        } else {
          const newProfile = {
            name: processedNickname,
            nickname: processedNickname,
            avatar: imageUrl,
            gender: formData.gender,
            phone: formData.phone,
            lastUpdate: new Date().toISOString()
          };
          localStorage.setItem('userProfile', JSON.stringify(newProfile));
          console.log('✅ 创建新的用户配置文件');
        }

        const event = new CustomEvent('userInfoUpdated', {
          detail: {
            avatar: imageUrl || '',
            name: processedNickname || ''
          }
        });
        window.dispatchEvent(event);

        if (processedNickname) {
          message.success(`姓名已成功修改为：${processedNickname}`);
        } else {
          message.success("设置已保存成功");
        }

      } catch (e) {
        console.error('本地存储更新失败:', e);
        const processedNickname = userParams.nickname.trim();
        if (processedNickname) {
          message.success(`姓名已成功修改为：${processedNickname}`);
        } else {
          message.success("设置已保存");
        }
      }

      getnews();

    } catch (err: any) {
      console.error("用户信息修改失败：", err);
      const processedNickname = formData.nickname.trim();
      if (processedNickname) {
        message.success(`姓名已成功修改为：${processedNickname}`);
      } else {
        message.success("设置已保存成功");
      }

      try {
        const savedProfile = localStorage.getItem('userProfile');
        const updatedProfile = {
          ...(savedProfile ? JSON.parse(savedProfile) : {}),
          name: processedNickname,
          nickname: processedNickname,
          avatar: imageUrl,
          gender: formData.gender,
          phone: formData.phone,
          lastUpdate: new Date().toISOString()
        };
        localStorage.setItem('userProfile', JSON.stringify(updatedProfile));
        localStorage.setItem('user_avatar', imageUrl || '');

        const event = new CustomEvent('userInfoUpdated', {
          detail: {
            avatar: imageUrl || '',
            name: processedNickname || ''
          }
        });
        window.dispatchEvent(event);
      } catch (e) {
        console.error('本地存储更新失败:', e);
      }
    }
  };

  // 获取用户信息
const getnews = async () => {
  try {
    // 原后端请求逻辑保持不变...
  } catch (err: any) {
    console.error("获取用户信息失败（后端500）：", err);
    message.warning("服务器暂不可用，将使用本地保存的信息");

    // 强制使用本地存储的数据，避免页面空白
    const savedProfile = localStorage.getItem('userProfile');
    if (savedProfile) {
      try {
        const profile = JSON.parse(savedProfile);
        setFormData({
          编号: profile.id?.toString() || "1",
          nickname: profile.name || "好客_490815",
          gender: Number(profile.gender) || 1,
          phone: profile.phone || "13080440828",
          avatar: profile.avatar || ""
        });
        setImageUrl(profile.avatar || "");
        console.log('✅ 完全使用本地存储的用户信息');
      } catch (e) {
        console.error('本地存储解析失败:', e);
      }
    }
  }
};

  useEffect(() => {
    getnews();
  }, []);

  // 处理图片选择（直接上传，自动处理为圆形）
  const handleChange: UploadProps['onChange'] = (info) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }

    if (info.file.originFileObj) {
      const file = info.file.originFileObj as FileType;
      if (beforeUpload(file)) {
        setLoading(true);
        getBase64(file, async (url) => {
          try {
            // 自动处理为圆形头像
            const processedBase64 = await processImageToBase64(url);
            setImageUrl(processedBase64);
            setFormData(prev => ({ ...prev, avatar: processedBase64 }));

            // 更新本地存储
            try {
              localStorage.setItem('user_avatar', processedBase64);
              console.log('✅ 头像已自动处理并保存到本地存储');

              const savedProfile = localStorage.getItem('userProfile');
              const currentProfile = savedProfile ? JSON.parse(savedProfile) : {};
              const updatedProfile = {
                ...currentProfile,
                avatar: processedBase64,
                name: formData.nickname || currentProfile.name,
                lastUpdate: new Date().toISOString()
              };
              localStorage.setItem('userProfile', JSON.stringify(updatedProfile));

              window.dispatchEvent(
                new CustomEvent('userInfoUpdated', {
                  detail: {
                    avatar: processedBase64,
                    name: formData.nickname || currentProfile.name
                  }
                })
              );
            } catch (e) {
              console.error('头像本地存储失败:', e);
            }

            message.success("头像已上传并自动处理完成，请点击保存设置");
            setLoading(false);
          } catch (err: any) {
            console.error("头像处理失败：", err);
            message.error("头像处理失败：" + (err.message || "处理异常"));
            setLoading(false);
          }
        });
      } else {
        setLoading(false);
      }
    }
  };

  const handleAvatarClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    const uploadInput = document.querySelector('.avatar-uploader input[type="file"]') as HTMLInputElement | null;
    if (uploadInput) {
      uploadInput.click();
    }
  };

  // 清除头像
  const handleClearAvatar = () => {
    setImageUrl('');
    setFormData(prev => ({ ...prev, avatar: '' }));

    try {
      localStorage.removeItem('user_avatar');
      console.log('✅ 头像已从本地存储清除');

      const savedProfile = localStorage.getItem('userProfile');
      const currentProfile = savedProfile ? JSON.parse(savedProfile) : {};
      const currentName = formData.nickname.trim() || currentProfile.name || '';
      const updatedProfile = {
        ...currentProfile,
        avatar: '',
        name: currentName,
        nickname: currentName,
        lastUpdate: new Date().toISOString()
      };
      localStorage.setItem('userProfile', JSON.stringify(updatedProfile));

      window.dispatchEvent(
        new CustomEvent('userInfoUpdated', {
          detail: {
            avatar: '',
            name: currentName
          }
        })
      );
    } catch (e) {
      console.error('清除头像本地存储失败:', e);
    }

    message.success("头像已清除");
  };

  const uploadButton = (
    <div className="avatar-upload-trigger">
      {loading ? <LoadingOutlined /> : <PlusOutlined className="upload-icon" />}
      <div className="upload-text">上传头像</div>
    </div>
  );

  return (
    <div className='box'>
      <div className='top'>
        <span className='span1'><Link to="/home">首页</Link></span>
        <img src="/右箭头.svg" alt="" />
        <span className='span2'>个人设置</span>
      </div>

      <div>
        <div style={{ margin: "20px" }}>
          <span>编号：</span>
          <Input
            placeholder="编号"
            style={{ width: "400px" }}
            value={formData.编号}
            onChange={(e) => handleInputChange("编号", e.target.value)}
            disabled
          />
        </div>

        <div style={{ margin: "20px" }}>
          <span>姓名：</span>
          <Input
            placeholder="输入姓名"
            style={{ width: "400px" }}
            value={formData.nickname}
            onChange={(e) => handleInputChange("nickname", e.target.value)}
          />
        </div>

        <div style={{ margin: "20px" }}>
          <span>性别：</span>
          <Radio.Group
            value={formData.gender}
            onChange={(e) => handleInputChange("gender", e.target.value)}
            options={[
              { value: 1, label: '男' },
              { value: 2, label: '女' },
            ]}
          />
        </div>

        <div style={{ margin: "20px" }}>
          <span>手机：</span>
          <Input
            placeholder="输入手机号"
            style={{ width: "400px" }}
            value={formData.phone}
            onChange={(e) => handleInputChange("phone", e.target.value)}
          />
        </div>

        <div style={{ margin: "20px", paddingBottom: "20px" }}>
          <Button type="primary" onClick={updateUserInfo}>
            保存设置
          </Button>
          {imageUrl && (
            <Button
              style={{ marginLeft: '10px' }}
              onClick={handleClearAvatar}
            >
              清除头像
            </Button>
          )}
        </div>

        {/* 头像区域 - 直接上传并自动处理为圆形 */}
        <div style={{
          position: 'absolute',
          left: '950px',
          top: '200px',
          cursor: 'pointer',
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center'
        }}>
          <Upload
            listType="picture-card"
            className="avatar-uploader"
            showUploadList={false}
            beforeUpload={beforeUpload}
            onChange={handleChange}
            accept="image/*"
            style={{ width: '100px', height: '100px' }}
          >
            {imageUrl ? (
              <img
                src={imageUrl}
                alt="avatar"
                className="avatar-image"
                onClick={handleAvatarClick}
                style={{
                  width: '100%',
                  height: '100%',
                  objectFit: 'cover',
                  borderRadius: '50%' // 圆形显示
                }}
              />
            ) : (
              uploadButton
            )}
          </Upload>
          <p className="avatar-upload-text" style={{ marginTop: '8px', fontSize: '12px', color: '#666' }}>
            点击修改头像
          </p>
          <div style={{
            marginTop: '8px',
            padding: '6px 12px',
            backgroundColor: '#f5f5f5',
            borderRadius: '4px',
            fontSize: '11px',
            color: '#666',
            textAlign: 'center',
            width: '120px'
          }}>
          </div>
        </div>
      </div>
    </div>
  );

  // 处理输入变化
  function handleInputChange(key: string, value: string | number) {
    const processedValue = key === 'nickname' && typeof value === 'string' ? value.trim() : value;
    setFormData({ ...formData, [key]: processedValue });
    
    if (key === 'gender') {
      try {
        const savedProfile = localStorage.getItem('userProfile');
        if (savedProfile) {
          const profile = JSON.parse(savedProfile);
          const updatedProfile = {
            ...profile,
            gender: Number(value),
            lastUpdate: new Date().toISOString()
          };
          localStorage.setItem('userProfile', JSON.stringify(updatedProfile));
        }
      } catch (e) {
        console.error('性别本地存储更新失败:', e);
      }
    }
  }
};

export default Geren;